// pages/distribute/distribute.js
var app = getApp();
var area = require('../../utils/lib/area.js');
var utils = require('../../utils/shop/formatShop.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    initInfo: {},
    disLevelInfo: {},
    item: {
      tdUrl: '/pages/tuandui/tuandui', //我的团队
      hyUrl: '/pages/member/member', //我的会员
      fxUrl: '/pages/distributelist/distributelist', //分销订单
      yjUrl: '/pages/yongjindetail/yongjindetail', //佣金明细
      dpUrl: '/pages/shopsetting/shopsetting', //店铺设置
      tgUrl: '/pages/extension/extension', //推广中心
      yongjinUrl: '/pages/yongjin/yongjin', //商家佣金
    },
    is_dis: '', //是否是分销商
    menkan_type: 1, //门槛类型
    goodslist: [], //门槛，购买指定商品（所有商品列表）
    picker_index: 1,
    select_lists: {},
    disabled: false,
    display: 'none',
    submit_text: '立即加入',

    area_arr_default: [
      { id: 0, name: '请选择省' },
      { id: 0, name: '请选择市' },
      { id: 0, name: '请选择县区' }
    ],
    area_arr: [],
    area_arr_idx: [],
    // 确认的选择省市县id
    choose_area_id: {
      province: 0,
      city: 0,
      area: 0
    },

    apply_info: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //隐藏加载框
    wx.hideLoading();
  },

  //页面加载
  load: function() {
    //执行用户成为分销逻辑
    var deal_distribute_data = {
      'UsersID': app.globalData.userInfo.Users_ID,
      'User_ID': app.globalData.userInfo.User_ID,
      'type': 'distribute',
      //'act': '/api/distribute/distribute.php?UsersID=' + app.globalData.userInfo.Users_ID,
      // User_ID: app.globalData.userInfo.User_ID
    };
    app.http_req(deal_distribute_data, app.globalData.init.api_url, 'POST', this.load_load);
    wx.stopPullDownRefresh();
    wx.hideNavigationBarLoading();
  },

  load_load: function(res) {
    wx.hideLoading();
    //更改标题
    // app.setNavBarTitle(app.globalData.userInfo.Is_Distribute == 1 ? '分销中心' : '分销门槛');

    //判断是否为分销商
    this.setData({
      is_dis: app.globalData.userInfo.Is_Distribute
    })
    if (app.globalData.userInfo.Is_Distribute == 1) { //是分销商 
      //获取用户分销信息
      var dataArgs = {
        act: "get_dis_info",
        User_ID: app.globalData.userInfo.User_ID,
      };
      app.http_req(dataArgs, app.globalData.init.api_url, 'POST', this.getDistribute);
    } else { //不是分销商
      var dataArgs = {
        act: "distribute_config"
      };
      //获取分销门槛设置，distribute_config 表中的数据
      app.http_req(dataArgs, app.globalData.init.api_url, 'POST', this.getMenkan);
    }
  },

  //分销初始化数据
  getDistribute: function(res) {
    if (res.errorCode === 0) {
      //累计佣金(小数位在上面)
      //小数位
      res.data.totalRecordMoney2 = utils.format_money(res.data.totalRecordMoney, 0);
      //整数位
      res.data.totalRecordMoney = utils.format_money(res.data.totalRecordMoney);

      //可提现佣金(小数位在上面)
      //小数位
      res.data.usersRecordMoney2 = utils.format_money(res.data.usersRecordMoney, 0);
      //整数位
      res.data.usersRecordMoney = utils.format_money(res.data.usersRecordMoney);

      //转换为string 
      res.data.disInfo.Shop_Logo = String(res.data.disInfo.Shop_Logo);
      //判断店铺头像是否为空或者null
      if (res.data.disInfo.Shop_Logo.length < 1 || res.data.disInfo.Shop_Logo != 'null') {
        //判断是否包含 'http'
        var reg_url = /^((https|http) ?:\/\/)[^\s]+$/;
        res.data.disInfo.User_HeadImg = reg_url.test(res.data.disInfo.Shop_Logo) ? res.data.disInfo.Shop_Logo : app.globalData.init.front_url + res.data.disInfo.Shop_Logo;
      }
      res.data.disInfo.Nick_Name = res.data.disInfo.Shop_Name ? res.data.disInfo.Shop_Name : res.data.disInfo.Nick_Name;
      this.setData({
        initInfo: res.data
      })
      /**
       * 把推荐人信息写入到缓存中
       */
      var recommender = new Object();
      recommender.name = res.data.disInfo.Parent_NickName;
      recommender.mobile = res.data.disInfo.Parent_Mobile;
      wx.setStorage({
        key: 'recommender',
        data: recommender
      });
    } else {
      wx.showModal({
        title: '错误',
        content: '服务器忙，稍后再试！',
      })
    }
  },

  /**
   * 分销门槛初始化
   * 只取默认第一个分销商设置
   */
  getMenkan: function(res) {
    if (res.errorCode === 0) {
      if (!res.data.dislevel || !res.data.dislevel[0]) {
        wx.showModal({
          title: '提示',
          content: '商家没有设置分销等级',
          showCancel: false
        })
        return false;
      }
      /**
       * 在此处理数据，如：手工申请的JSON字符串需要处理
       */
      var dislist = res.data.dislevel[0];
      //根据不同类型处理相关数据
      switch (parseInt(dislist['Level_LimitType'])) {
        case 0:
          //直接购买
          dislist['Remark'] = '需支付 ' + parseFloat(dislist['Level_LimitValue']) + '元'
          break;
        case 1:
          //消费额
          //消费额字符
          var LimitValue = dislist['Level_LimitValue'].split("|");
          /***
           * 判断是总消费，还是一次性消费，
           * 0：总消费
           * 1：一次性消费
           */
          var Consume_Type = parseInt(LimitValue[0]);
          dislist['Consume_Type'] = Consume_Type;
          if (Consume_Type == 0) {
            dislist['Remark'] = '需要在商城总消费' + LimitValue[1] + '元';
          } else {
            dislist['Remark'] = '需要一次性消费' + LimitValue[1] + '元';
          }
          break;
        case 2:
          //购买商品
          var LimitValue = dislist['Level_LimitValue'].split("|");
          /***
           * 判断是任意商品，还是指定商品，
           * 0：任意商品
           * 1：指定商品
           */
          var Good_Type = parseInt(LimitValue[0]);
          dislist['Good_Type'] = Good_Type;
          if (Good_Type == 0) {
            dislist['Remark'] = '购买任意商品即可';
            dislist['Url'] = '/pages/index/index';
          } else {
            dislist['Remark'] = '需要购买以下任意一种商品';
            //购买指定商品,根据接口获取指定的商品信息
            dislist['Good_Ids'] = LimitValue[0];
            var detailArgs = {
              act: 'get_pro',
              Products_ID: LimitValue[1]
            };
            //查询产品详情
            app.http_req(detailArgs, app.globalData.init.api_url, 'POST', this.get_goods);
          }
          break;
        case 5:
          //手动申请
          dislist['Remark'] = '请填写表单申请';

          dislist['Distribute_Form'] = JSON.parse(dislist.Distribute_Form);
          var select_arrays = [];
          for (var fi in dislist['Distribute_Form']) {
            // 地区选择
            if (fi == 'DisplayLocaltion' && dislist['Distribute_Form'][fi] == 1) {
              this.area_init();
            }
            if (dislist['Distribute_Form'][fi]['Type'] && dislist['Distribute_Form'][fi]['Type'] == 'select') {
              dislist['Distribute_Form'][fi]['Value'] = '请选择' + dislist['Distribute_Form'][fi]['Name'] + '|' + dislist['Distribute_Form'][fi]['Value'];
              var select_array = dislist['Distribute_Form'][fi]['Value'].split("|");
              dislist['Distribute_Form'][fi]['Value'] = select_array;
              var temp = new Object();
              temp.index = 0;
              temp.name = dislist['Distribute_Form'][fi]['Name'];
              temp.options = select_array;
              select_arrays.push(temp);
            }
          }

          this.setData({
            select_lists: select_arrays,
            disLevelInfo: dislist['Distribute_Form']
          });

          /**
           * 查询之前是否审核过，如果申请过，则需要根据结果来判断，立即加入，驳回重新提交，待审核三种可能
           * 
           * */
          var detailArgs = {
            action: 'getmanualorder',
            User_ID: app.globalData.userInfo.User_ID ? app.globalData.userInfo.User_ID : 0,
            uri: '/api/' + app.globalData.userInfo.Users_ID + '/distribute/ajax/'
          };
          //查询申请详情
          app.http_req(detailArgs, app.globalData.init.api_url, 'POST', this.getmanualorder);

          break;
        default:
          dislist['Remark'] = '无门槛';

      }
      this.setData({
        initInfo: dislist,
        menkan_type: res.data.disconfig.Distribute_Type
      })
    } else {
      wx.showModal({
        title: '错误',
        content: '服务器忙，稍后再试！',
        showCancel: false
      })
    }
  },

  // 初始化地区
  area_init(apply_info = '') {
    //地区数据处理
    let area_arr_default = this.data.area_arr_default;
    let area_arr = [];
    let area_arr_idx = [];
    if (apply_info != '' && apply_info['Applyfor_Province_ID'] > 0 && apply_info['Applyfor_City_ID'] > 0) {
      area_arr = [
        utils.array_change(area.area[0]['0'], area_arr_default[0]),
        utils.array_change(area.area[0]['0,' + apply_info['Applyfor_Province_ID']], area_arr_default[1]),
        utils.array_change(area.area[0]['0,' + apply_info['Applyfor_Province_ID'] + ',' + apply_info['Applyfor_City_ID']], area_arr_default[2])
      ];
      area_arr_idx = [
        utils.get_arr_index(area_arr[0], apply_info['Applyfor_Province_ID']),
        utils.get_arr_index(area_arr[1], apply_info['Applyfor_City_ID']),
        utils.get_arr_index(area_arr[2], apply_info['Applyfor_Area_ID'])
      ];
      this.setData({
        choose_area_id: {
          province: apply_info['Applyfor_Province_ID'],
          city: apply_info['Applyfor_City_ID'],
          area: apply_info['Applyfor_Area_ID']
        }
      });
    } else {
      area_arr = [
        utils.array_change(area.area[0]['0'], area_arr_default[0]),
        utils.array_change([], area_arr_default[1]),
        utils.array_change([], area_arr_default[2])
      ];
      area_arr_idx = [0, 0, 0];
    }

    this.setData({
      area_arr: area_arr,
      area_arr_idx: area_arr_idx
    });
  },

  //处理省市区联动信息
  addressChange: function (columnValue, is_confirm = 0) {
    let area_arr_default = this.data.area_arr_default;
    var p_arr = this.data.area_arr[0];
    var p_id = p_arr[columnValue[0]]['id'];
    var c_arr = utils.array_change(p_id > 0 ? area.area[0][0 + ',' + p_id] : [], area_arr_default[1]);
    var c_id = c_arr[columnValue[1]]['id'];
    var a_arr = utils.array_change(c_id > 0 ? area.area[0][0 + ',' + p_id + ',' + c_id] : [], area_arr_default[2]);

    this.setData({
      area_arr: [
        p_arr,
        c_arr,
        a_arr
      ],
      area_arr_idx: columnValue,
    });
    if (is_confirm) {
      this.setData({
        choose_area_id: {
          province: p_id,
          city: c_id,
          area: a_arr[columnValue[2]].id
        }
      });
    }
  },

  //选择收获地址三级联动后确定按钮动作
  choose_area: function (e) {
    this.addressChange(e.detail.value, 1);
  },

  //选择收货地址
  choose_area_column: function (e) {
    var column = e.detail.column;  //修改的列
    var index = e.detail.value;    //选择列的下标（从0开始）

    var columnValue = [
      column == 0 ? index : this.data.area_arr_idx[0],
      column == 0 ? 0 : (column == 1 ? index : this.data.area_arr_idx[1]),
      column == 0 || column == 1 ? 0 : index
    ];
    this.addressChange(columnValue);
  },

  // 取消选择
  choose_area_reset(e) {
    let choose_area_id = this.data.choose_area_id;
    let apply_info = {
      Applyfor_Province_ID: choose_area_id.province || 0,
      Applyfor_City_ID: choose_area_id.city || 0,
      Applyfor_Area_ID: choose_area_id.area || 0,
    };
    this.area_init(apply_info);
  },

  /**
   * 处理获取商品列表（主要针对购买指定商品选项）
   */
  get_goods: function(res) {
    if (res.errorCode == 0) {
      this.setData({
        goodslist: utils.formatShop(app.globalData.init.front_url, res.data)
      })
    }
  },

  //提交手动申请
  formSubmit: function(form) {
    var form_info = form.detail.value;
    for (var i in form_info) {
      if (!form_info[i]) {
        wx.showToast({
          title: '请输入' + i,
          icon: 'none'
        });
        return false;
      }
    }

    let area_select = {};
    for (var formItem in this.data.disLevelInfo) {
      var itemValue = this.data.disLevelInfo[formItem];
      if (formItem == 'DisplayLocaltion' && itemValue == 1) {
        // 选择地区
        let choose_area_id = this.data.choose_area_id
        if (choose_area_id.province == 0 || choose_area_id.city == 0 || choose_area_id.area == 0) {
          wx.showToast({
            title: '请选择所在区域',
            icon: 'none'
          });
          return false;
        } else {
          area_select = choose_area_id;
        }
      }
      if (itemValue.Type && itemValue.Type == 'select') {
        form_info[itemValue.Name] = itemValue.Value[form_info[itemValue.Name]];
      }
    }
    //姓名
    var Applyfor_Name = '';
    //电话
    var Applyfor_Mobile = '';
    //自定义字段集合
    var other_info = {};

    for (var i in form_info) {
      if (i == '姓名') {
        Applyfor_Name = form_info[i];
      } else if (i == '电话') {
        Applyfor_Mobile = form_info[i];
        //正则验证手机的是否合法
        if (!utils.check_mobile(form_info[i])) {
          wx.showToast({
            title: '手机号格式错误',
            icon: 'none'
          });
          return false;
        }
      } else {
        other_info[i] = form_info[i];
      }
    }

    var dataArgs = {
      User_ID: app.globalData.userInfo.User_ID ? app.globalData.userInfo.User_ID : 0,
      JSON: JSON.stringify(other_info),
      Name: Applyfor_Name,
      Mobile: Applyfor_Mobile,
      action: 'manual_tj',
      uri: '/api/' + app.globalData.userInfo.Users_ID + '/distribute/ajax/'
    };
    dataArgs = Object.assign(dataArgs, area_select);
    this.setData({
      disabled: true
    });
    app.http_req(dataArgs, app.globalData.init.api_url, 'POST', this.addManual);
  },
  /**
   * 提交手动申请数据
   */
  addManual: function(res) {
    if (res.status == 1) {
      wx.showToast({
        title: res.msg,
        icon: 'success'
      })
      this.setData({
        disabled: true,
        submit_text: '待审核',
        display: 'none',
      })
    } else {
      this.setData({
        disabled: false
      });
      wx.showModal({
        title: '提示',
        content: typeof res.msg != 'undefined' ? res.msg : '提交失败',
        showCancel: false
      })
    }
  },

  /**
   * 判断是否提交了申请
   */
  getmanualorder: function(res) {
    if (res.errorCode == 0) {
      var apply_info = res.data;
      apply_info.Applyfor_form = apply_info.Applyfor_form && typeof apply_info.Applyfor_form != 'object' ? JSON.parse(apply_info.Applyfor_form) : apply_info.Applyfor_form;
      var select_lists = this.data.select_lists;
      for (let i in select_lists) {
        if (apply_info.Applyfor_form[select_lists[i].name]) {
          for (let j in select_lists[i].options) {
            if (apply_info.Applyfor_form[select_lists[i].name] == select_lists[i].options[j]) {
              select_lists[i].index = j;
            }
          }
        }
      }
      if (apply_info.Refuse_Be && utils.isJsonString(apply_info.Refuse_Be)) {
        apply_info.Refuse_Be = JSON.parse(apply_info.Refuse_Be);
        apply_info.Refuse_Be = apply_info.Refuse_Be ? apply_info.Refuse_Be[apply_info.Refuse_Be.length - 1] : '';
      }

      // 地区信息处理
      this.area_init(apply_info);

      //已申请过分销商   status -1:驳回 0:待审核 1:已审核
      if (apply_info.status == '0') {
        //待通过，禁用提交按钮，改变按钮文字：待审核，隐藏驳回声明
        this.setData({
          disabled: true,
          submit_text: '待审核',
          display: 'none',
          apply_info: apply_info,
          select_lists: select_lists
        })
      } else if (apply_info.status == '-1') {
        this.setData({
          //驳回，启用提交按钮，改变按钮文字：驳回 重新提交，显示驳回声明
          disabled: false,
          submit_text: '驳回 重新提交',
          display: 'block',
          apply_info: apply_info,
          select_lists: select_lists
        })
      } else {
        //已通过审核，暂不处理
        this.setData({
          disabled: true,
          submit_text: '您已通过审核',
          display: 'none',
          apply_info: apply_info,
          select_lists: select_lists
        })
      }
    }
  },

  /**
   * 下拉框改变
   */
  bindPickerChange: function(e) {
    if (e.detail.value == '0') {
      //当有下拉框未选择时，禁用提交按钮
      // this.setData({ 
      //   disabled: true 
      // });
      wx.showToast({
        title: e.target.dataset.data[0],
        icon: 'loading'
      });
      return false;
    } else {
      //当下拉框选择非空时，启用用提交按钮
      // this.setData({
      //   disabled: false
      // });
    }
    var curindex = e.target.dataset.curindex
    this.data.select_lists[curindex].index = e.detail.value
    this.setData({
      select_lists: this.data.select_lists
    })
  },

  //直接购买成为分销商
  paytodis: function(e) {
    var Level_ID = e.currentTarget.dataset.level_id;

    var dataArgs = {
      uri: '/api/' + app.globalData.userInfo.Users_ID + '/distribute/ajax/',
      action: 'deal_level_order',
      User_ID: app.globalData.userInfo.User_ID,
      LevelID: Level_ID
    };
    app.http_req(dataArgs, app.globalData.init.api_url, 'POST', this.paytodis_callback);
  },

  //支付成为分销商回调
  paytodis_callback: function(res) {
    if (res.status == 1) {
      var dataArgs = {
        act: 'get_dis_order',
        User_ID: app.globalData.userInfo.User_ID,
        Order_ID: res.orderid
      };
      app.http_req(dataArgs, app.globalData.init.api_url, 'POST', this.get_dis_order_callback);
    } else {
      wx.showModal({
        title: '错误',
        content: typeof res.msg != 'undefined' ? res.msg : '订单提交失败',
        showCancel: false
      })
    }
  },

  //获取分销订单详情回调
  get_dis_order_callback: function(res) {
    if (res.errorCode == 0) {
      var orderInfo = res.data[0];
      if (orderInfo.Order_Status == 1) {
        var postData = {
          Order_ID: orderInfo['Order_CreateTime'] + orderInfo['Order_ID'], //因notify_distribute中会切掉前10位字符
          totalPrice: orderInfo['Order_TotalPrice'],
          Order_Type: 'distribute'
        };
        app.unifiedorder(postData);
      } else {
        wx.showModal({
          title: '错误',
          content: '订单不是待付款状态，不能付款',
          showCancel: false
        })
      }
    } else {
      wx.showModal({
        title: '错误',
        content: '获取订单详情失败',
        showCancel: false
      })
    }
  },

  /**
   * 跳转到首页
   */
  gohome: function() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  /**
   * 跳转产品页
   */
  goods_detail: function(e) {
    var proid = e.currentTarget.dataset.proid;
    var ptflag = e.currentTarget.dataset.ptflag;
    wx.navigateTo({
      url: ptflag ? '../detail_pt/detail_pt?proid=' + proid : '../detail/detail?proid=' + proid
    });
  },

  /**
   * 跳转佣金页
   */
  yongjin: function(e) {
    wx.navigateTo({
      url: '/pages/yongjin/yongjin'
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    //检查用户是否登录
    if (!app.globalData.userInfo) {
      wx.showLoading({
        title: '加载中',
      })
      this.setData({
        is_dis: ''
      });
      app.login('', this.load, 'distribute');
    } else {
      if (app.globalData.userInfo.Is_Distribute == 1) { //已是分销商
        this.load();
      } else {
        wx.showLoading({
          title: '加载中',
        })
        this.setData({
          is_dis: ''
        });
        //这里用重新获取用户信息（以防用户成为分销商后用户数据不更新）
        app.login('reLogin', this.load, 'distribute');
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    //显示加载导航条
    wx.showNavigationBarLoading();
    //初始化数据 (防止数据重复)
    this.setData({
      initInfo: {},
      disLevelInfo: {},
      is_dis: '', //是否是分销商
      menkan_type: 1, //门槛类型
      goodslist: [], //门槛，购买指定商品（所有商品列表）
      picker_index: 1,
      select_lists: {},
      disabled: false,
      display: 'none',
      submit_text: '立即加入',
    });
    this.load();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
})